<template>
  <view class="house-detail-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle" size="40" color="#21d59d"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 房屋详情 -->
    <view v-else-if="houseDetail" class="detail-content">
      <!-- 房屋基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <u-icon name="home" size="20" color="#21d59d"></u-icon>
          <text class="title-text">房屋信息</text>
        </view>
        <view class="info-card">
          <view class="house-header">
            <view class="house-number">
              <text class="number-text">{{ houseDetail.houseNum }}号</text>
              <view class="status-badge" :class="{ 'rented': houseDetail.renterId }">
                <text class="status-text">{{ houseDetail.renterId ? '租用' : '自住' }}</text>
              </view>
            </view>
            <view class="orientation-info">
              <text class="orientation">{{ houseDetail.orientation }}</text>
            </view>
          </view>
          
          <view class="house-info-grid">
            <view class="info-item">
              <text class="label">建筑面积</text>
              <text class="value">{{ houseDetail.floorSpace }}㎡</text>
            </view>
            <view class="info-item">
              <text class="label">套内面积</text>
              <text class="value">{{ houseDetail.insideSpace }}㎡</text>
            </view>
            <view class="info-item">
              <text class="label">公摊面积</text>
              <text class="value">{{ houseDetail.sharedSpace }}㎡</text>
            </view>
            <view class="info-item">
              <text class="label">户型</text>
              <text class="value">{{ houseDetail.room }}室{{ houseDetail.hall }}厅{{ houseDetail.toilet }}卫</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 位置信息 -->
      <view class="info-section">
        <view class="section-title">
          <u-icon name="map" size="20" color="#21d59d"></u-icon>
          <text class="title-text">位置信息</text>
        </view>
        <view class="info-card">
          <view class="location-info">
            <view class="location-item">
              <text class="label">小区名称</text>
              <text class="value">{{ houseDetail.cellName }}</text>
            </view>
            <view class="location-item">
              <text class="label">楼栋</text>
              <text class="value">{{ houseDetail.buildingName }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 业主信息 -->
      <view class="info-section">
        <view class="section-title">
          <u-icon name="account" size="20" color="#21d59d"></u-icon>
          <text class="title-text">业主信息</text>
        </view>
        <view class="info-card">
          <view class="owner-info">
            <view class="owner-item">
              <text class="label">业主姓名</text>
              <text class="value">{{ houseDetail.ownerName }}</text>
            </view>
            <view class="owner-item">
              <text class="label">联系电话</text>
              <text class="value phone" @click="callPhone(houseDetail.ownerPhone)">{{ houseDetail.ownerPhone }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 出租信息（如果有） -->
      <view v-if="houseRentInfo" class="info-section">
        <view class="section-title">
          <u-icon name="calendar-fill" size="20" color="#21d59d"></u-icon>
          <text class="title-text">出租信息</text>
        </view>
        <view class="info-card">
          <view class="rent-info">
            <view class="rent-item">
              <text class="label">详细地址</text>
              <text class="value">{{ houseRentInfo.address }}</text>
            </view>
            <view class="rent-item">
              <text class="label">租金</text>
              <text class="value price">¥{{ houseRentInfo.price }}/月</text>
            </view>
            <view class="rent-item">
              <text class="label">出租类型</text>
              <text class="value">{{ houseRentInfo.type === 1 ? '押一付一' : '押一付三' }}</text>
            </view>
            <view class="rent-item">
              <text class="label">状态</text>
              <view class="status-badge" :class="{ 'active': houseRentInfo.status === 1 }">
                <text class="status-text">{{ houseRentInfo.status === 1 ? '已出租' : '待出租' }}</text>
              </view>
            </view>
            <view v-if="houseRentInfo.remark" class="rent-item">
              <text class="label">备注</text>
              <text class="value">{{ houseRentInfo.remark }}</text>
            </view>
            <view class="rent-item">
              <text class="label">创建时间</text>
              <text class="value">{{ houseRentInfo.createTime }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 租户信息（如果有） -->
      <view v-if="houseDetail.renterId" class="info-section">
        <view class="section-title">
          <u-icon name="calendar-fill" size="20" color="#ff9800"></u-icon>
          <text class="title-text">租户信息</text>
        </view>
        <view class="info-card">
          <view class="renter-info">
            <view class="renter-item">
              <text class="label">租户姓名</text>
              <text class="value">{{ houseDetail.renterName }}</text>
            </view>
            <view class="renter-item">
              <text class="label">联系电话</text>
              <text class="value phone" @click="callPhone(houseDetail.renterPhone)">{{ houseDetail.renterPhone }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 返回按钮 -->
      <view class="action-section">
        <view class="action-buttons">
          <!-- 只有自住房屋且没有出租信息时才显示设置出租按钮 -->
          <button v-if="!houseDetail.renterId && !houseRentInfo" class="action-btn primary" @click="showRentForm = true">
            <u-icon name="calendar-fill" size="16" color="white"></u-icon>
            <text>设置出租</text>
          </button>
          <button class="action-btn secondary" @click="goBack">
            <u-icon name="arrow-left" size="16" color="#21d59d"></u-icon>
            <text>返回</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <view class="error-icon">❌</view>
      <text class="error-text">加载失败</text>
      <text class="error-desc">请检查网络连接后重试</text>
      <button class="retry-btn" @click="fetchHouseDetail">重新加载</button>
    </view>

    <!-- 出租信息设置弹窗 -->
    <u-popup 
      :show="showRentForm" 
      mode="center" 
      :round="20"
      :closeable="true"
      @close="showRentForm = false"
    >
      <view class="rent-form-popup">
        <view class="popup-header">
          <text class="popup-title">设置出租信息</text>
        </view>
        
        <view class="popup-content">
          <!-- 详细地址 -->
          <view class="form-item">
            <text class="form-label">详细地址</text>
            <u-input 
              v-model="rentForm.address"
              placeholder="请输入详细地址"
              :border="false"
              class="form-input"
            ></u-input>
          </view>

          <!-- 租金 -->
          <view class="form-item">
            <text class="form-label">租金（元/月）</text>
            <u-input 
              v-model="rentForm.price"
              placeholder="请输入租金"
              type="number"
              :border="false"
              class="form-input"
            ></u-input>
          </view>

          <!-- 出租类型 -->
          <view class="form-item">
            <text class="form-label">出租类型</text>
            <view class="form-input" @click="showTypeActionSheet = true">
              <text class="input-text" :class="{ 'placeholder': !rentForm.selectedType }">
                {{ rentForm.selectedType || '请选择出租类型' }}
              </text>
              <u-icon name="arrow-down" size="16" color="#999"></u-icon>
            </view>
          </view>

          <!-- 备注 -->
          <view class="form-item">
            <text class="form-label">备注</text>
            <u-textarea 
              v-model="rentForm.remark"
              placeholder="请输入备注信息（选填）"
              :maxlength="200"
              :autoHeight="true"
              class="form-textarea"
            ></u-textarea>
          </view>
        </view>

        <view class="popup-footer">
          <button class="cancel-btn" @click="showRentForm = false">取消</button>
          <button class="confirm-btn" @click="submitRent" :disabled="!canSubmitRent">确认</button>
        </view>
      </view>
    </u-popup>

    <!-- 出租类型选择器 -->
    <u-action-sheet 
      :show="showTypeActionSheet" 
      :actions="typeActions" 
      @select="onTypeSelect"
      @close="showTypeActionSheet = false"
      title="选择出租类型"
    ></u-action-sheet>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { HouseApi } from '@/api';
import type { HouseDetail, HouseRentInfo } from '@/api/house/types';

// 响应式数据
const loading = ref(true);
const houseDetail = ref<HouseDetail | null>(null);
const houseId = ref<number>(0);
const houseRentInfo = ref<HouseRentInfo | null>(null);

// 弹窗相关
const showRentForm = ref(false);
const showTypeActionSheet = ref(false);

// 出租表单数据
const rentForm = ref({
  address: '',
  price: '',
  selectedType: '',
  remark: ''
});

// 出租类型选项
const rentTypes = [
  { label: '押一付一', value: 1 },
  { label: '押一付三', value: 3 }
];

// 计算属性
const typeActions = computed(() => {
  return rentTypes.map(type => ({
    name: type.label,
    value: type.value
  }));
});

const canSubmitRent = computed(() => {
  return rentForm.value.address.trim() && 
         rentForm.value.price.trim() && 
         rentForm.value.selectedType;
});

// 获取房屋详情
async function fetchHouseDetail() {
  try {
    loading.value = true;
    
    const response = await HouseApi.getHouseDetail({ houseId: houseId.value });
    
    if (response.code === 0) {
      houseDetail.value = response.data;
    } else {
      uni.showToast({
        title: response.message || '获取房屋详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取房屋详情失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
}

// 检查房屋出租状态
async function checkHouseRentStatus() {
  try {
    const response = await HouseApi.checkHouseRent({ houseId: houseId.value });
    
    if (response.code === 0) {
      // 如果返回的出租信息中的房屋ID与当前房屋ID一致，说明有出租信息
      if (response.data && response.data.houseId === houseId.value) {
        houseRentInfo.value = response.data;
      } else {
        houseRentInfo.value = null;
      }
    } else {
      houseRentInfo.value = null;
    }
  } catch (error) {
    console.error('检查房屋出租状态失败:', error);
    houseRentInfo.value = null;
  }
}

// 拨打电话
function callPhone(phone: string) {
  uni.makePhoneCall({
    phoneNumber: phone,
    fail: (err) => {
      console.error('拨打电话失败:', err);
      uni.showToast({
        title: '拨打电话失败',
        icon: 'none'
      });
    }
  });
}

// 返回上一页
function goBack() {
  uni.navigateBack();
}

// 出租类型选择确认
function onTypeSelect(item: { name: string, value: number }) {
  rentForm.value.selectedType = item.name;
  showTypeActionSheet.value = false;
}

// 提交出租信息
async function submitRent() {
  if (!canSubmitRent.value) {
    uni.showToast({
      title: '请完善所有必填信息',
      icon: 'none'
    });
    return;
  }

  try {
    const rentType = rentTypes.find(type => type.label === rentForm.value.selectedType);
    
    if (!houseDetail.value || !rentType) {
      uni.showToast({
        title: '数据异常，请重试',
        icon: 'none'
      });
      return;
    }
    
    const requestData = {
      houseId: houseId.value,
      ownerId: houseDetail.value.ownerId,
      cellId: houseDetail.value.cellId,
      address: rentForm.value.address.trim(),
      price: Number(rentForm.value.price),
      type: rentType.value,
      remark: rentForm.value.remark.trim()
    };

    const response = await HouseApi.setHouseRent(requestData);
    
    if (response.code === 0) {
      uni.showToast({
        title: '出租信息设置成功',
        icon: 'success'
      });
      
      // 关闭弹窗并重新获取房屋详情和出租状态
      showRentForm.value = false;
      resetRentForm();
      await Promise.all([
        fetchHouseDetail(),
        checkHouseRentStatus()
      ]);
    } else {
      uni.showToast({
        title: response.message || '设置失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('设置出租信息失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
  }
}

// 重置出租表单
function resetRentForm() {
  rentForm.value = {
    address: '',
    price: '',
    selectedType: '',
    remark: ''
  };
}

// 页面加载时获取数据
onMounted(() => {
  // 从页面参数中获取房屋ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const options = currentPage.options || {};
  
  if (options.houseId) {
    houseId.value = parseInt(options.houseId);
    // 同时获取房屋详情和出租状态
    Promise.all([
      fetchHouseDetail(),
      checkHouseRentStatus()
    ]);
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.house-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.info-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.house-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.house-number {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.number-text {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  background: #21d59d;
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-badge.rented {
  background: #ff9800;
}

.orientation {
  font-size: 28rpx;
  color: #666;
  background: #f0f0f0;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
}

.house-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.label {
  font-size: 24rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.value.phone {
  color: #21d59d;
  text-decoration: underline;
}

.location-info, .owner-info, .renter-info, .rent-info {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.location-item, .owner-item, .renter-item, .rent-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.location-item:last-child, .owner-item:last-child, .renter-item:last-child, .rent-item:last-child {
  border-bottom: none;
}

.value.price {
  color: #ff6b35;
  font-weight: bold;
  font-size: 30rpx;
}

.status-badge.active {
  background: #21d59d;
}

.status-badge:not(.active) {
  background: #ff9800;
}

.action-section {
  margin-top: 20rpx;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.action-btn.primary {
  background: #21d59d;
  color: white;
}

.action-btn.secondary {
  background: white;
  color: #21d59d;
  border: 2rpx solid #21d59d;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500rpx;
  padding: 40rpx;
}

.error-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.error-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.error-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  line-height: 1.5;
  margin-bottom: 40rpx;
}

.retry-btn {
  background: #21d59d;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

/* 弹窗样式 */
.rent-form-popup {
  width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  padding: 30rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.form-input {
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 80rpx;
}

.input-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.input-text.placeholder {
  color: #999;
}

.form-textarea {
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 24rpx;
  min-height: 120rpx;
}

.popup-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #21d59d;
  color: white;
}

.confirm-btn:disabled {
  background: #ccc;
  color: #999;
}
</style>
